package org.example.warlock;

import org.redisson.Redisson;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class WarlockApplication {
    public static void main(String[] args) throws InterruptedException {
        var applicationContext = SpringApplication.run(WarlockApplication.class);
        var bean = applicationContext.getBean(Redisson.class);
        System.out.println(bean);
        //以下顺序必须保证
        //1. 声明redis实现的信号量
        var semaphore = bean.getPermitExpirableSemaphore("my");
        //2. 设置信号量的大小, 重复设置没关系;  也就是说如果已经初始化了, 则不会再次设置
        System.out.println(semaphore.trySetPermits(5));
        //3. 设置信号量的过期时间, 必须要设置, 不然Redis里就会有一大堆无限期的key
        System.out.println(semaphore.expire(3, TimeUnit.MINUTES));

        //4. 获取信号量, 获取的时候, 一定要指定过期时间, 并要记录下id
        var permitId = semaphore.tryAcquire(1, 2, TimeUnit.MINUTES);
        System.out.println(permitId);
        //5. 可选步骤, 给这个信号量手动设置租期
        System.out.println(
                semaphore.updateLeaseTime("e2ecaa8ecc56972787b78f022c038b82", 5, TimeUnit.SECONDS));

        //6. 归还信号量的permit
        System.out.println(semaphore.tryRelease(permitId));

//
//        for (int i = 0; i < 2; i++) {
//            System.out.println(semaphore.tryAcquire(2, TimeUnit.SECONDS));
//        }
//        System.out.println("trySetPermits  5");
//        System.out.println(semaphore.trySetPermits(5));
////        System.out.println(semaphore.updateLeaseTime("my", 5, TimeUnit.MINUTES));
//
//        for (int i = 0; i < 6; i++) {
//            System.out.println(semaphore.tryAcquire(i, TimeUnit.SECONDS));
//        }
//
//        System.out.println("trySetPermits 10 ");
//        System.out.println(semaphore.trySetPermits(10));
//
//        semaphore.trySetPermits(10);
//
//        System.out.println(semaphore.tryAcquire());


    }
}